import {Component, OnInit} from '@angular/core';
import {ModalService, ToastService} from 'ng-zorro-antd-mobile';
import {ActivatedRoute, Router} from '@angular/router';
import {HttpClient} from '@angular/common/http';
import {EventService} from '../common/service/event.service';

@Component({
    selector: 'app-application',
    templateUrl: './application.page.html',
    // styleUrls: ['./application.page.less'],
})
export class ApplicationPage implements OnInit {

    public localhostVersion; // 本地应用的版本号
    public localhostAppName; // 本地应用的名称
    public serverVersion; // 服务器配置的应用版本号
    public menu: Array<any> = []; // 菜单
    public temp: Array<any> = []; // 临时菜单代替 grid
    public pcControlMenu: Array<any> = []; // pc端控制的菜单
    public showGroupPage: boolean = true; // 展示分组页面（true-分组页面；false-平铺页面）
    public applicationTileMenuData: Array<any> = []; // 应用平铺页面的菜单数据
    public applicationTileDragulaMenuData: Array<any> = []; // 应用平铺页面(可拖动)的菜单数据
    public everyLevelDivWidth: string = '107px'; // 应用平铺页面(可拖动)每个横向菜单的宽度
    public applicationTileMenuColumn: number = 3; // 应用平铺页面的菜单一行默认3个菜单
    public applicationTileMenuColSize: number = 4; // 保证applicationTileMenuColumn*applicationTileMenuColSize=12


    public user;   // 当前登录用户的信息
    public userCode; // 当前登录用户的code
    // 当前用户绑定的设备信息
    public userBindDeviceInfo = {
        eqptUuid: null,     // 设备唯一标志符
        eqptManufacturer: null, // 设备制造商
        eqptName: null,    // 设备名称
        eqptSystem: null, // 设备系统
        eqptSystemVersion: null,  // 设备操作系统版本号
    };
    // 当前设备的信息
    public currDeviceInfo = {
        eqptUuid: null,     // 设备唯一标志符
        eqptManufacturer: null, // 设备制造商
        eqptName: null,    // 设备名称
        eqptSystem: null, // 设备系统
        eqptSystemVersion: null,  // 设备操作系统版本号
    };

    public selectTheme = null; // 缓存中设置的主题


    public grid = [
        {url: 'productShow', key: 'mobile#productShow', title: '产品秀', img: '产品秀', bgc: '#3499f6', times: 0},
        {url: 'malfunctionRepair', key: 'mobile#malfunctionRepair', title: '故障报修', img: '故障报修', bgc: '#ffc300', times: 0},
        {url: 'dynamicCertification', key: 'mobile#dynamicCertification', title: '动态鉴伪', img: '动态鉴伪', bgc: '#3499f6', times: 0},
        {url: 'suggestions', key: 'mobile#suggestions', title: '投诉建议', img: '投诉建议', bgc: '#ffc300', times: 0},
        {url: 'productArchive', key: 'mobile#productArchive', title: '产品档案', img: '产品档案', bgc: '#ff9000', times: 0},
        {url: 'qualityTraceability', key: 'mobile#qualityTraceability', title: '资产档案', img: '资产档案', bgc: '#ff9000', times: 0}
    ];

    public scanText; // 扫码识别到的数据

    constructor(
        private router: Router,
        private route: ActivatedRoute,
        private toast: ToastService,
        private http: HttpClient,
        private modal: ModalService,
        private eventService: EventService,
    ) {
        // 需要接收ScanPage传递来的参数,并显示在视图中
        // 当前页面监听扫码事件广播
        this.eventService.eventEmit.on('scanPageCloseEvent', (result) => {
            console.log('执行 result=', result);
            this.scanText = result;
            alert(this.scanText);
        });


        // this.getMenuData();

        this.applicationTileDragulaMenuData = this.grid;
    }


    ionViewWillEnter() {
        this.toast.hide();
    }

    /**
     * 根据终端页面的宽度调整页面横向显示的菜单个数
     * judgeClientWidth()
     * @param g
     */
    showMenuClientWidth(clientWidth) {
        console.log('终端宽度 clientWidth = ', clientWidth);
        if (this.selectTheme == 'gridAuto') {
            // 常见的手机屏宽度
            if (clientWidth < 450) {
                this.applicationTileMenuColumn = 3;
                this.applicationTileMenuColSize = 4;
            }
            if (clientWidth >= 450 && clientWidth < 650) {
                this.applicationTileMenuColumn = 4;
                this.applicationTileMenuColSize = 3;
            }
            // 常见的平板屏幕宽度
            if (clientWidth >= 650) {
                this.applicationTileMenuColumn = 6;
                this.applicationTileMenuColSize = 2;
            }
        }
        console.log(' this.applicationTileMenuColumn AAAA = ', this.applicationTileMenuColumn);
        // 重新排列菜单数据
        let a = [];
        let b = [];
        this.applicationTileMenuData.map((item, index) => {
            if (((index + 1) % this.applicationTileMenuColumn) !== 0) {
                a = a.concat(item);
                if (index + 1 === this.applicationTileMenuData.length) {
                    b.push(a);
                }
            } else {
                a = a.concat(item);
                b.push(a);
                a = [];
            }
        });
        this.applicationTileMenuData = b;
        console.log('最终 this.applicationTileMenuData =', this.applicationTileMenuData);
        // 每个div宽度 = （clientWidth - 16 -横向div个数*2*2px）/ 横向div个数
        this.everyLevelDivWidth = ((clientWidth - 16 - this.applicationTileMenuColumn * 4) / this.applicationTileMenuColumn) + 'px';
        console.log('everyLevelDivWidth = ', this.everyLevelDivWidth);
    }

    ngOnInit() {
    }

    /**
     * 初始化完组件视图及其子视图之后调用(dom 操作放在这个里面)(重 要)
     * ngAfterViewInit()
     */
    ngAfterViewInit() {

    }

    ionViewDidEnter() {
        console.log('ionViewDidEnter');

        // 根据设置的主题展示相应的菜单布局
        // console.log('取缓存中的主题 selectTheme = ', localStorage.getItem('selectTheme'));
        // this.selectTheme = localStorage.getItem('selectTheme');

        switch (this.selectTheme) {
            // 1、未设置主题。使用默认主题-平铺自适应（gridAuto）
            case '':
            case 'null':
            case null:
                // 赋默认值,分组显示（group）
                // this.selectTheme = 'group';
                // localStorage.setItem('selectTheme', 'group');
                // this.showGroupPage = true;

                // 赋默认值,平铺自适应显示（gridAuto）
                this.selectTheme = 'gridAuto';
                localStorage.setItem('selectTheme', 'gridAuto');
                this.showGroupPage = false;
                this.showMenuClientWidth(document.body.clientWidth);
                break;
            // 2、已经设置主题。
            case 'group':
                this.showGroupPage = true;
                break;
            case 'grid2':
                this.showGroupPage = false;
                this.applicationTileMenuColumn = 2;
                this.showMenuClientWidth(document.body.clientWidth);
                break;
            case 'grid3':

                break;
            case 'grid4':
                this.showGroupPage = false;
                this.applicationTileMenuColumn = 4;
                this.showMenuClientWidth(document.body.clientWidth);
                break;
            case 'grid5':
                this.showGroupPage = false;
                this.applicationTileMenuColumn = 5;
                this.showMenuClientWidth(document.body.clientWidth);
                break;
            case 'grid6':
                this.showGroupPage = false;
                this.applicationTileMenuColumn = 6;
                this.showMenuClientWidth(document.body.clientWidth);
                break;
            case 'gridAuto':
                this.showGroupPage = false;
                this.showMenuClientWidth(document.body.clientWidth);
                break;
            default:
                this.showGroupPage = true;
        }

    }

    // 过滤缓存中的数据
    filterStorageMenuData() {
        // console.log('this.applicationTileDragulaMenuData AAAAA= ', this.applicationTileDragulaMenuData);
        let tempArr = JSON.parse(localStorage.getItem('applicationTileDragulaMenuData'));
        let tempArr2 = [];
        let tempArr3 = [];
        // 判断缓存中是否存在之前排序过的菜单
        if (tempArr && tempArr.length > 0) {
            // 缓存中存在
            // 检查缓存中的排序菜单是否已经被pc端禁止显示了
            let exist = false;
            tempArr.map((tempArrItem, tempArrIndex) => {
                this.applicationTileDragulaMenuData.map(menuItem => {
                    if (tempArrItem.url === menuItem.url) {
                        tempArr2.push(tempArrItem);
                        return;
                    }
                });
            });
            // console.log('缓存中的排序菜单 tempArr = ', tempArr);
            // console.log('缓存中的排序菜单 tempArr2 = ', tempArr2);
            // 检查pc端显示的菜单在缓存中不存在
            this.applicationTileDragulaMenuData.map(menuItem => {
                tempArr2.map(tempArrItem => {
                    if (menuItem.url === tempArrItem.url) {
                        exist = true;
                        tempArr3.push(tempArrItem);
                        return;
                    }
                });
                if (!exist) {
                    menuItem.times = 0;
                    tempArr3.push(menuItem);
                } else {
                    exist = false;
                }
            });

            this.applicationTileDragulaMenuData = tempArr3;
            // 重新根据times排序
            this.applicationTileDragulaMenuData.sort(this.getSortFun('desc', 'times'));
            localStorage.setItem('applicationTileDragulaMenuData', JSON.stringify(this.applicationTileDragulaMenuData));
        } else {
            this.applicationTileDragulaMenuData.map(item => {
                item.times = 0; // 使用频率
            });
            localStorage.setItem('applicationTileDragulaMenuData', JSON.stringify(this.applicationTileDragulaMenuData));
        }

        console.log('this.applicationTileDragulaMenuData BBBBB= ', this.applicationTileDragulaMenuData);
    }

    /**
     *@描述 平铺菜单下公共模块的路由跳转
     *@参数  route
     *@返回值
     *@创建人  wzq
     *@创建时间  2020/7/22
     *@修改人和其它信息
     */
    routerJump(route: any) {
        this.router.navigate([route]);
        // this.router.navigate(['/online/tabs/tab3'], {relativeTo: this.route, replaceUrl: true});
    }

    // ******************* 移动端菜单部分 start ******************** //
    getMenuData() {
        // this.processReportService.findUserRole(userId).then(res0 => {
        // console.log('获取的菜单列表数据 res0 = ', res0);
        let res0 = {
            'code': 200,
            'msg': 'success',
            'data': [{
                'createuser': '超级管理员',
                'createtime': '2020-09-08 17:01:11',
                'lastmodifieduser': '超级管理员',
                'lastmodifiedtime': '2020-10-26 15:12:08',
                'id': '939bf72b-1e71-4499-8a02-7a67d1aa106c',
                'code': '01',
                'name': '测试角色',
                'state': '1',
                'note': null,
                // 'menu': '[{"title":"工艺建模","icon":"book","key":"mopm","dir":true,"children":[{"title":"工厂布局","key":"/index/mopm/plantlayout","dir":true,"children":[{"title":"物流路径管理","url":"/index/mopm/plantlayoutmaintain","key":"/index/mopm/plantlayoutmaintain","isLeaf":true,"buttons":[{"label":"新增","value":"add","checked":false},{"label":"修改","value":"edit","checked":false},{"label":"删除","value":"delete","checked":false},{"label":"启用","value":"affirm","checked":false},{"label":"停用","value":"noaffirm","checked":false}],"checked":true},{"title":"物流路径查询","url":"/index/mopm/logisticspathoperationquery","key":"/index/mopm/logisticspathoperationquery","isLeaf":true,"checked":true},{"title":"标准节点定义","url":"/index/mopm/stditem","key":"/index/mopm/stditem","isLeaf":true,"checked":true}],"checked":true,"expanded":false},{"title":"工艺路线","key":"mopm/routing","dir":true,"children":[{"title":"工艺路线管理","url":"/index/mopm/routingmaintain","key":"/index/mopm/routingmaintain","isLeaf":true,"checked":true},{"title":"工艺路线分配","url":"/index/mopm/routingusage","key":"/index/mopm/routingusage","isLeaf":true,"checked":true},{"title":"工艺路线查询","url":"/index/mopm/routingconsult","key":"/index/mopm/routingconsult","isLeaf":true,"checked":true},{"title":"工艺路线导入","url":"/index/mopm/routingimport","key":"/index/mopm/routingimport","isLeaf":true,"checked":true}],"checked":true},{"title":"产品配套","key":"mopm/materialsetmanage","dir":true,"children":[{"title":"产品配套管理","url":"/index/mopm/materialset","key":"/index/mopm/materialset","isLeaf":true,"checked":true}],"checked":true},{"title":"标准工序","key":"mopm/stdoperation","dir":true,"children":[{"title":"标准工序管理","url":"/index/mopm/stdoperationmanage","key":"/index/mopm/stdoperationmanage","isLeaf":true,"checked":true},{"title":"标准工序分类","url":"/index/mopm/stdoperationsort","key":"/index/mopm/stdoperationsort","isLeaf":true,"checked":true},{"title":"标准工序导入","url":"/index/mopm/stdoperationimport","key":"/index/mopm/stdoperationimport","isLeaf":true,"checked":true}],"checked":true},{"title":"物料清单","key":"/mopm/bom","dir":true,"children":[{"title":"物料清单管理","url":"/index/mopm/bommaintain","key":"/index/mopm/bommaintain","isLeaf":true,"checked":true},{"title":"物料清单分配","url":"/index/mopm/bomdistribution","key":"/index/mopm/bomdistribution","isLeaf":true,"checked":true},{"title":"物料清单分类","url":"/index/mopm/bomsort","key":"/index/mopm/bomsort","isLeaf":true,"checked":true}],"checked":true}],"checked":true,"expanded":true},{"title":"生产调度","icon":"carry-out","key":"mopsworkerorder","dir":true,"children":[{"title":"工单管理","key":"/index/mops/workerorder","dir":true,"children":[{"title":"工单管理","url":"/index/mops/workerordermanager","key":"/index/mops/workerordermanager","isLeaf":true,"buttons":[{"label":"新增","value":"add","checked":false},{"label":"复制","value":"copy","checked":false},{"label":"批量复制","value":"cybatch","checked":false},{"label":"订单接收","value":"receive","checked":false},{"label":"发布","value":"release","checked":false},{"label":"取消发布","value":"cancelRelease","checked":false},{"label":"齐套分析","value":"analysis","checked":false},{"label":"序列号","value":"sn","checked":false},{"label":"生成序列号","value":"newsn","checked":false},{"label":"联查序列号","value":"findsn","checked":false},{"label":"状态处理","value":"state","checked":false},{"label":"冻结","value":"freeze","checked":false},{"label":"解冻","value":"unfreeze","checked":false},{"label":"联查文档","value":"findfile","checked":false},{"label":"打印","value":"print","checked":false},{"label":"导出","value":"export","checked":false}],"checked":true}],"checked":true},{"title":"派工管理","key":"/index/mops/operationplan","dir":true,"children":[{"title":"工序计划","url":"/index/mops/operationplanmgr","key":"/index/mops/operationplanmgr","isLeaf":true,"buttons":[{"label":"新增","value":"add","checked":false},{"label":"保存","value":"save","checked":false},{"label":"取消","value":"rollback","checked":false},{"label":"编辑","value":"edit","checked":false},{"label":"排程","value":"schedue","checked":false},{"label":"委外申请","value":"outsource","checked":false},{"label":"工序调整","value":"opupdate","checked":false}],"checked":true},{"title":"工序派工","url":"/index/mops/operationplandispatch","key":"/index/mops/operationplandispatch","isLeaf":true,"buttons":[{"label":"派工","value":"dispatch","checked":false},{"label":"发布","value":"release","checked":false},{"label":"委外申请","value":"outsource","checked":false}],"checked":true}],"checked":true}],"checked":true},{"title":"生产执行","icon":"compass","key":"/index/mope","dir":true,"children":[{"title":"工序控制","key":"/index/mope/process","dir":true,"children":[{"title":"工序信息采集","url":"/index/mope/processinformation","key":"/index/mope/processinformation","isLeaf":true,"checked":true},{"title":"派工信息采集","url":"/index/mope/processoperation","key":"/index/mope/processoperation","isLeaf":true,"checked":true}],"checked":true},{"title":"返工返修","key":"/index/mope/repairtask","dir":true,"children":[{"title":"返工管理","url":"/index/mope/reworkmanage","key":"/index/mope/reworkmanage","isLeaf":true,"checked":true},{"title":"返修管理","url":"/index/mope/repairmanage","key":"/index/mope/repairmanage","isLeaf":true,"checked":true}],"checked":true}],"checked":true},{"title":"过程检验","key":"indexmoqm","icon":"dashboard","dir":true,"children":[{"title":"检验模板","key":"/index/moqm/template","dir":true,"children":[{"title":"结构化模板管理","url":"/index/moqm/templatemain","key":"/index/moqm/templatemain","isLeaf":true,"checked":true},{"title":"数据模型定义","url":"/index/moqm/datamodel","key":"/index/moqm/datamodel","isLeaf":true,"checked":true}],"checked":true},{"title":"检验任务","key":"/index/moqm/special","dir":true,"children":[{"title":"专检","url":"/index/moqm/specialinspection","key":"/index/moqm/specialinspection","isLeaf":true,"checked":true},{"title":"二次报检","url":"/index/moqm/twoinspection","key":"/index/moqm/twoinspection","isLeaf":true,"checked":true},{"title":"自检","url":"/index/moqm/selfchecking","key":"/index/moqm/selfchecking","isLeaf":true,"checked":true}],"checked":true},{"title":"基础数据","key":"/index/moqm/inspect","dir":true,"children":[{"title":"检验类型","url":"/index/moqm/inspecttype","key":"/index/moqm/inspecttype","isLeaf":true,"checked":true},{"title":"检验项目分类","url":"/index/moqm/inspectItemSort","key":"/index/moqm/inspectItemSort","isLeaf":true,"checked":true},{"title":"检验项目","url":"/index/moqm/inspectitems","key":"/index/moqm/inspectitems","isLeaf":true,"checked":true}],"checked":true}],"checked":true},{"title":"工程文档","icon":"crown","key":"indexmodm","dir":true,"children":[{"title":"文档管理","key":"/index/modmmanage","dir":true,"children":[{"title":"文档管理","url":"/index/modm/manage","key":"/index/modm/manage","isLeaf":true,"buttons":[{"label":"上传","value":"upload","checked":true},{"label":"取消","value":"cancel","checked":true},{"label":"修改","value":"edit","checked":true},{"label":"删除","value":"delete","checked":true},{"label":"保存","value":"save","checked":true},{"label":"预览","value":"preview","checked":true},{"label":"下载","value":"download","checked":true},{"label":"发布","value":"release","checked":true},{"label":"取消发布","value":"cancelRelease","checked":true}],"checked":true,"selected":false},{"title":"文档查阅","url":"/index/modm/consult","key":"/index/modm/consult","isLeaf":true,"buttons":[{"label":"下载","value":"download","checked":true},{"label":"预览","value":"preview","checked":true}],"checked":true,"selected":true},{"title":"文档预览","url":"/index/modm/previewwindow","key":"/index/modm/previewwindow","hidden":true,"isLeaf":true,"checked":true}],"checked":true,"expanded":true},{"title":"基础数据","key":"/index/modmbd","dir":true,"children":[{"title":"文档目录","url":"/index/modm/filedirectory","key":"/index/modm/filedirectory","isLeaf":true,"checked":true},{"title":"文档类型","url":"/index/modm/filetype","key":"/index/modm/filetype","isLeaf":true,"checked":true}],"checked":true},{"title":"操作日志","key":"/index/modmlog","dir":true,"children":[{"title":"操作日志","url":"/index/modm/fileoperationlog","key":"/index/modm/fileoperationlog","isLeaf":true,"checked":true}],"checked":true}],"checked":true,"expanded":true},{"title":"条码管理","key":"mobm","dir":true,"children":[{"title":"基础数据","key":"/index/mobm/dadabase","dir":true,"children":[{"title":"条码规则定义","url":"/index/mobm/snrule","key":"/index/mobm/snrule","isLeaf":true,"checked":true}],"checked":true},{"title":"条码打印","key":"/index/mobm/snprint","dir":true,"children":[{"title":"工人条码打印","url":"/index/mobm/worker","key":"/index/mobm/worker","isLeaf":true,"checked":true},{"title":"工序条码打印","url":"/index/mobm/process","key":"/index/mobm/process","isLeaf":true,"checked":true},{"title":"工单条码打印","url":"/index/mobm/workorder","key":"/index/mobm/workorder","isLeaf":true,"checked":true},{"title":"序列号条码打印","url":"/index/mobm/serialnumber","key":"/index/mobm/serialnumber","isLeaf":true,"checked":true}],"checked":true}],"checked":true},{"title":"异常管理","key":"moam","dir":true,"children":[{"title":"异常管理","key":"/index/exception","dir":true,"children":[{"title":"异常登记","url":"/index/moam/exceptionregister","key":"/index/moam/exceptionregister","isLeaf":true,"checked":true},{"title":"异常处理","url":"/index/moam/exceptionhandling","key":"/index/moam/exceptionhandling","isLeaf":true,"checked":true},{"title":"异常关闭","url":"/index/moam/exceptionclose","key":"/index/moam/exceptionclose","isLeaf":true,"checked":true}],"checked":true},{"title":"基础数据","key":"moam/exceptionbase","dir":true,"children":[{"title":"异常类型","url":"/index/moam/exceptiontype","key":"/index/moam/exceptiontype","isLeaf":true,"checked":true},{"title":"异常等级","url":"/index/moam/exceptionlevel","key":"/index/moam/exceptionlevel","isLeaf":true,"checked":true},{"title":"异常内容","url":"/index/moam/exceptioncontent","key":"/index/moam/exceptioncontent","isLeaf":true,"checked":true},{"title":"异常原因","url":"/index/moam/exceptionreason","key":"/index/moam/exceptionreason","isLeaf":true,"checked":true},{"title":"处理措施","url":"/index/moam/exceptionaction","key":"/index/moam/exceptionaction","isLeaf":true,"checked":true}],"checked":true}],"checked":true},{"title":"报表管理","icon":"layout","key":"indexmosa","dir":true,"children":[{"title":"报表设计","key":"/index/mosa/reportdesign","dir":true,"children":[{"title":"分析报表定义","isLeaf":true,"key":"/index/mosa/reportmanage","url":"/index/mosa/reportmanage","buttons":[{"label":"新增","value":"add","checked":false},{"label":"编辑","value":"edit","checked":false},{"label":"删除","value":"delete","checked":false},{"label":"模板设计","value":"modeldesign","checked":false}],"checked":true},{"title":"分析看板定义","isLeaf":true,"key":"/index/mosa/dashmanage","url":"/index/mosa/dashmanage","buttons":[{"label":"新增","value":"add","checked":false},{"label":"编辑","value":"edit","checked":false},{"label":"删除","value":"delete","checked":false},{"label":"模板设计","value":"modeldesign","checked":false}],"checked":true},{"title":"打印格式定义","isLeaf":true,"url":"/index/mosa/printformat","key":"/index/mosa/printformat","buttons":[{"label":"新增","value":"add","checked":false},{"label":"编辑","value":"edit","checked":false},{"label":"删除","value":"delete","checked":false},{"label":"模板设计","value":"modeldesign","checked":false}],"checked":true},{"title":"报表类别维护","isLeaf":true,"url":"/index/mosa/reportsort","key":"/index/mosa/reportsort","checked":true},{"title":"数据源定义","isLeaf":true,"url":"/index/mosa/dbconnection","key":"/index/mosa/dbconnection","checked":true}],"checked":true},{"title":"报表中心","key":"/index/mosa/reportdesign","dir":true,"children":[{"title":"报表看板","isLeaf":true,"url":"/index/mosa/mgr","key":"/index/mosa/mgr","checked":true}],"checked":true}],"checked":true},{"title":"定制记录","icon":"layout","key":"/index/record","checked":true,"dir":true,"children":[{"title":"界面配置中心","key":"/index/main/model","dir":true,"checked":true,"children":[{"title":"界面模型维护","icon":"layout","checked":true,"isLeaf":true,"url":"/index/model","key":"/index/model"}]},{"title":"定制记录管理","key":"/index/morp/record","dir":true,"checked":true,"children":[{"title":"记录模板管理","icon":"layout","checked":true,"isLeaf":true,"url":"/index/moqm/prodtemplatemain","key":"/index/moqm/prodtemplatemain"},{"title":"数据模型定义","icon":"layout","checked":true,"isLeaf":true,"url":"/index/moqm/proddatamodel","key":"/index/moqm/proddatamodel"}]}]},{"title":"工厂建模","icon":"apartment","admin":true,"key":"indexmofm","dir":true,"children":[{"title":"工作组织","admin":true,"key":"/index/mofmfffff","dir":true,"children":[{"title":"工厂","url":"/index/mofm/factory","key":"/index/mofm/factory","isLeaf":true,"admin":true,"checked":true},{"title":"场所","url":"/index/mofm/place","key":"/index/mofm/place","isLeaf":true,"admin":true,"checked":true},{"title":"工作中心","url":"/index/mofm/workcenter","key":"/index/mofm/workcenter","isLeaf":true,"admin":true,"checked":true},{"title":"工作单元","url":"/index/mofm/workunit","key":"/index/mofm/workunit","isLeaf":true,"admin":true,"checked":true},{"title":"组织类型定义","url":"/index/mofm/orgtype","key":"/index/mofm/orgtype","isLeaf":true,"admin":true,"checked":true}],"checked":true},{"title":"班组管理","key":"/index/mofmworkteam","dir":true,"children":[{"title":"班组定义","url":"/index/mofm/workteam","key":"/index/mofm/workteam","isLeaf":true,"checked":true}],"checked":true}],"checked":true},{"title":"基础数据","icon":"appstore","key":"indexmobd","admin":true,"dir":true,"children":[{"title":"组织信息","admin":true,"key":"/index/mobd/company","dir":true,"children":[{"title":"公司信息","url":"/index/mobd/companyinfo","key":"/index/mobd/companyinfo","isLeaf":true,"admin":true,"checked":true},{"title":"部门信息","url":"/index/mobd/departmentinfo","key":"/index/mobd/departmentinfo","isLeaf":true,"admin":true,"checked":true},{"title":"人员类型","url":"/index/mobd/persontype","key":"/index/mobd/persontype","isLeaf":true,"admin":true,"checked":true},{"title":"人员信息","url":"/index/mobd/personinfo","key":"/index/mobd/personinfo","isLeaf":true,"admin":true,"checked":true}],"checked":true},{"title":"物料信息","key":"/index/mobd/material","dir":true,"children":[{"title":"物料定义","url":"/index/mobd/materialmanage","key":"/index/mobd/materialmanage","isLeaf":true,"checked":true},{"title":"物料查询","url":"/index/mobd/materialquery","key":"/index/mobd/materialquery","isLeaf":true,"checked":true},{"title":"物料分类","url":"/index/mobd/materialsort","key":"/index/mobd/materialsort","isLeaf":true,"checked":true},{"title":"物料类型","url":"/index/mobd/materialtype","key":"/index/mobd/materialtype","isLeaf":true,"checked":true}],"checked":true},{"title":"计量单位","key":"/index/mobd/measureunits","dir":true,"children":[{"title":"计量单位","url":"/index/mobd/measureunitsmanage","key":"/index/mobd/measureunitsmanage","isLeaf":true,"checked":true},{"title":"计量单位组","url":"/index/mobd/measureunitstype","key":"/index/mobd/measureunitstype","isLeaf":true,"checked":true}],"checked":true},{"title":"资源信息","key":"/index/mobdressort","dir":true,"children":[{"title":"资源分类","url":"/index/mobd/ressort","key":"/index/mobd/ressort","isLeaf":true,"checked":true}],"checked":true},{"title":"项目信息","key":"/index/mobdprojectphase","dir":true,"children":[{"title":"项目信息","url":"/index/mobd/projectinfo","key":"/index/mobd/projectinfo","isLeaf":true,"checked":true},{"title":"项目分类","url":"/index/mobd/projectsort","key":"/index/mobd/projectsort","isLeaf":true,"checked":true},{"title":"项目类型","url":"/index/mobd/projecttype","key":"/index/mobd/projecttype","isLeaf":true,"checked":true},{"title":"项目阶段","url":"/index/mobd/projectphase","key":"/index/mobd/projectphase","isLeaf":true,"checked":true},{"title":"项目产出物","url":"/index/mobd/projectmaterial","key":"/index/mobd/projectmaterial","isLeaf":true,"checked":true},{"title":"任务号","url":"/index/mobd/projectwbsinfo","key":"/index/mobd/projectwbsinfo","isLeaf":true,"checked":true},{"title":"任务类型","url":"/index/mobd/projectwbstype","key":"/index/mobd/projectwbstype","isLeaf":true,"checked":true}],"checked":true},{"title":"系统设置","key":"/index/systemset","dir":true,"children":[{"title":"系统设置","url":"/index/mobd/systemset","key":"/index/mobd/systemset","isLeaf":true,"checked":true}],"checked":true}],"checked":true},{"title":"数据权限","icon":"appstore","admin":true,"key":"index/mosa","dir":true,"children":[{"title":"数据权限","admin":true,"key":"/index/moaofffff","dir":true,"children":[{"title":"数据权限配置","url":"/index/functionmenu","key":"/index/functionmenu","isLeaf":true,"admin":true,"checked":true},{"title":"数据权限管理","url":"/index/roledatamanage","key":"/index/roledatamanage","isLeaf":true,"admin":true,"checked":true},{"title":"数据权限维护","url":"/index/auobjmamnage","key":"/index/auobjmamnage","isLeaf":true,"admin":true,"checked":true}],"checked":true}],"checked":true},{"title":"移动应用","icon":"mobile","key":"mobilemenu","dir":true,"hidden":true,"mobile":true,"children":[{"title":"生产执行","key":"mobile01","dir":true,"children":[{"url":"mobile#processStarts","key":"mobile#processStarts","title":"工序开工","img":"工序开工","bgc":"#3499f6","isLeaf":true,"checked":true},{"url":"mobile#processReport","key":"mobile#processReport","title":"工序报工","img":"工序报工","bgc":"#ffc300","isLeaf":true,"checked":true},{"url":"mobile#repairTaskManager","key":"mobile#repairTaskManager","title":"返工管理","img":"返工管理","bgc":"#3499f6","isLeaf":true,"checked":true}],"checked":true},{"title":"质量检验","key":"mobile02","dir":true,"children":[{"url":"mobile#processInspection","key":"mobile#processInspection","title":"工序检验","img":"工序检验","bgc":"#4dcfe1","isLeaf":true,"checked":true},{"url":"mobile#secondaryInspection","key":"mobile#secondaryInspection","title":"二次报检","img":"二次报检","bgc":"#ffc300","isLeaf":true,"checked":true}],"checked":true},{"title":"过程跟踪","key":"mobile03","dir":true,"children":[{"url":"mobile#productionProgress","key":"mobile#productionProgress","title":"生产进度","img":"生产进度","bgc":"#ff9000","isLeaf":true,"checked":true}],"checked":true},{"title":"工程文档","key":"nobile04","dir":true,"children":[{"url":"mobile#fileReference","key":"mobile#fileReference","title":"文档查阅","img":"文档查阅","bgc":"#ffc300","isLeaf":true,"checked":true}],"checked":true}],"checked":true}]'
                'menu': '[{"title":"移动应用","icon":"mobile","key":"mobilemenu","dir":true,"hidden":true,"mobile":true,"children":[{"title":"生产执行","key":"mobile01","dir":true,"children":[{"url":"mobile#processStarts","key":"mobile#processStarts","title":"产品秀","img":"产品秀","bgc":"#3499f6","isLeaf":true,"checked":true},{"url":"mobile#processReport","key":"mobile#processReport","title":"故障报修","img":"故障报修","bgc":"#ffc300","isLeaf":true,"checked":true},{"url":"mobile#repairTaskManager","key":"mobile#repairTaskManager","title":"动态鉴伪","img":"动态鉴伪","bgc":"#3499f6","isLeaf":true,"checked":true}],"checked":true},{"title":"质量检验","key":"mobile02","dir":true,"children":[{"url":"mobile#processInspection","key":"mobile#processInspection","title":"投诉建议","img":"投诉建议","bgc":"#4dcfe1","isLeaf":true,"checked":true},{"url":"mobile#secondaryInspection","key":"mobile#secondaryInspection","title":"产品档案","img":"产品档案","bgc":"#ffc300","isLeaf":true,"checked":true}],"checked":true},{"title":"资产档案","key":"mobile03","dir":true,"children":[{"url":"mobile#productionProgress","key":"mobile#productionProgress","title":"资产档案","img":"资产档案","bgc":"#ff9000","isLeaf":true,"checked":true}],"checked":true}],"checked":true}]'
            }]
        };
        const res = JSON.parse(JSON.stringify(res0)).data;
        if (res && res.length > 0) {
            for (let i = 0; i < res.length; i++) {
                let r = res[i];
                if (!(r['menu'] && r['menu'].length > 0)) {
                    continue;
                }
                let m = JSON.parse(r['menu']);
                if (this.menu && this.menu.length == 0) {
                    this.menu = m; // menu初始值为[]
                } else {
                    if (this.menu != null && this.menu.length > 0 && m != null && m.length > 0) {
                        this.circleMenu(this.menu, m);
                    } else {
                        this.menu = m;
                    }
                }
            }
        }
        //TODO:以下两函数逻辑过于繁杂，可能有重复。但功能完好，不确定能否精简
        this.menuForCheck(this.menu);
        this.shakeUnChecked(this.menu);
        // console.log(' menu = ', this.menu);
        // 过滤出 移动端的菜单
        this.mobileMenuFilter(this.menu);

        // }, err => {
        //   console.log('获取的菜单列表数据 err = ', err);
        // });
    }

    /**
     * 移动端菜单过滤
     * mobileMenuFilter()
     * @param menu
     */
    mobileMenuFilter(menu: Array<any>) {
        if (menu && menu.length > 0) {
            menu.map(item => {
                if (item.mobile) {
                    this.pcControlMenu = item.children;
                }
            });
            if (this.pcControlMenu.length <= 0) {
                this.modal.alert(`提示`, `没有给您分配菜单，请联系管理员！`, [
                    {text: '取消', onPress: () => console.log('点击了取消')},
                    {
                        text: '确定', onPress: () => {
                        }
                    }
                ]);
            } else {
                this.mobileMenu(this.pcControlMenu);
            }
        }
    }

    /**
     * 移动端菜单
     * mobileMenu()
     * @param menu
     */
    mobileMenu(menu: Array<any>) {
        const test = menu;
        test.map(item => {
            item.children.map(res => {
                let strUrl = res.url;
                let search = '#';
                let end = strUrl.lastIndexOf(search); // 获得字符串的结束位置
                let result = strUrl.substring(end + 1); // 截取字符串
                res.url = result;
            });
        });
        this.pcControlMenu = test;
        console.log('移动端菜单 temp = ', this.pcControlMenu);

        // 应用平铺页面菜单数据
        let a = JSON.parse(JSON.stringify(this.pcControlMenu));
        a.map(item => {
            this.applicationTileMenuData = this.applicationTileMenuData.concat(item.children);
        });
        // 应用平铺页面(可拖动)的菜单数据
        this.applicationTileDragulaMenuData = JSON.parse(JSON.stringify(this.applicationTileMenuData));
        console.log('应用平铺页面菜单数据 this.applicationTileMenuData = ', this.applicationTileMenuData);
        // 过滤缓存中的数据
        this.filterStorageMenuData();
        this.showMenuClientWidth(document.body.clientWidth);
    }

    /**
     *@描述 点击菜单频率+1,（times+1）
     *@参数  row
     *@返回值
     *@创建人  wzq
     *@创建时间  2020/7/24
     *@修改人和其它信息
     */
    addTimes(data, row) {
        console.log('点击 data = ', data);
        // console.log('点击 row = ', row);
        this.applicationTileDragulaMenuData.map(item => {
            if (item.url === row.url) {
                item.times++;
            }
        });
        console.log('点击后 this.applicationTileDragulaMenuData = ', this.applicationTileDragulaMenuData);
        let tempArr = JSON.parse(JSON.stringify(this.applicationTileDragulaMenuData));
        // 重新根据times排序
        tempArr.sort(this.getSortFun('desc', 'times'));
        localStorage.setItem('applicationTileDragulaMenuData', JSON.stringify(tempArr));
        // this.showMenuClientWidth(document.body.clientWidth);
    }

    // 根据字段property重新按字段order排序
    getSortFun(order, property) {
        return (a, b) => {
            let value1 = a[property];
            let value2 = b[property];
            return (order === 'asc') ? (value1 - value2) : (value2 - value1);
        };
    }


    // 删除无权限节点
    shakeUnChecked(menu: Array<any>) {
        for (let i = menu.length; i--;) {
            if (menu[i]['checked']) {
                if (menu[i]['children']) {
                    this.shakeUnChecked(menu[i]['children']);
                }
            } else {
                menu.splice(i, 1);
            }
        }
    }

    // 校验checked 主要是子节点勾选，勾选父节点
    menuForCheck(menu: Array<any>) {
        for (let i = menu.length; i--;) {
            if (menu[i]) {
                if (menu[i].checked) {
                } else if (menu[i].hasOwnProperty('children') && menu[i].children.length > 0) {
                    if (this.itemChecked(menu[i]['children'])) {
                        menu[i]['checked'] = true;
                        this.menuForCheck(menu[i]['children']);
                    }
                }
            }
        }
    }

    // 校验子集，是否为checked
    itemChecked(menu: Array<any>) {
        let b = false;
        for (let i = menu.length; i--;) {
            if (menu[i].checked) {
                b = true;
                break;
            } else {
                if (menu[i].hasOwnProperty('children') && menu[i].children.length > 0) {
                    b = this.itemChecked(menu[i]['children']);
                    if (b) {
                        break;
                    }
                }
            }
        }
        return b;
    }

    // 循环检测,合并两个menu
    circleMenu(menu: Array<any>, m: Array<any>) {
        //FIXME:当多个角色基础菜单不一致时，可能会检测不到多出来的菜单项。目前从业务角度避免
        menu.map(item => {
            if (!(item.hasOwnProperty('checked') && item.checked)) {
                item.checked = this.findByKey(m, item.key.toString());
            }
            if (item.hasOwnProperty('children') && item.children.length > 0) {
                this.circleMenu(item.children, m);
            }
        });
    }

    // 查找树中该url是否checked
    findByKey(menu: Array<any>, key: string) {
        let r = false;
        for (let i = menu.length - 1; i >= 0; i--) {
            let m = menu[i];
            if (m.key.toString() == key) {
                if (m.hasOwnProperty('checked') && m.checked) {
                    r = true;
                    break;
                }
            } else {
                if (m.hasOwnProperty('children') && m.children.length > 0) {
                    r = this.findByKey(m.children, key);
                    if (r) {
                        break;
                    }
                }
            }
        }
        return r;
    }

    // ******************* 移动端菜单部分 end ******************** //

    /**
     * 判断是否弹出更新提示
     * judgeVersion(local, server)
     */
    judgeVersion(localhostVersion, serverVersion): boolean {
        let arrLocal: [] = localhostVersion.split('.');
        let arrServer: [] = serverVersion.split('.');
        let strLocal: string = '';
        let strServer: string = '';
        for (let i = 0; i < arrLocal.length; i++) {
            strLocal += arrLocal[i];
        }
        for (let i = 0; i < arrLocal.length; i++) {
            strServer += arrServer[i];
        }
        if (Number(strServer) > Number(strLocal)) {
            return true;
        } else {
            return false;
        }
    }

    data(row: Element) {
        return JSON.parse(JSON.stringify(row));
    }

}
